/**
 * @param {Express.Request} req
 * @param {Express.Response} res
 * @param {NextFunction} next
 */
function restfulMiddleware(req, res, next) {
  res.sendPacket = ({ code = 0, msg = "", data }) => {
    res.status(200);
    res.json({ code, msg, data });
  };
  res.sendSuccess = (data, msg = "", code = 0) => {
    res.sendPacket({ code, msg, data });
  };
  res.sendFailure = (msg = "Unknown Error", code = -1, data) => {
    res.sendPacket({ code, msg, data });
  };
  next();
}

/**
 * @param {Error} err
 * @param {Express.Request} req
 * @param {Express.Response} res
 * @param {NextFunction} next
 */
function errorHandler(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  let responseData = err.data;
  if (process.env.ENVTYPE === "development") {
    responseData = err.stack;
    console.error(err);
  }
  res.sendFailure("[catch] " + err.message, err.code, responseData);
}

module.exports = {
  restfulMiddleware,
  errorHandler,
};
